import 'package:fluent_ui/fluent_ui.dart';
import 'package:flutter/material.dart' show DataCell, DataColumn;
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';

import '../../components/buttons.dart';
import '../../components/data_table.dart';
import '../../model/school_class_model.dart';
import '../../utils/date_utils.dart';
import '../app/app_dict_data.dart';
import 'school_class_view_edit.dart';
import 'school_class_view_model.dart';

///学校班级:视图列表
class SchoolClassViewList extends StatefulWidget {
  final String schoolId;

  const SchoolClassViewList({super.key, required this.schoolId});

  @override
  State<SchoolClassViewList> createState() => _SchoolClassViewListState();
}

class _SchoolClassViewListState extends State<SchoolClassViewList> {
  final queryFormKey = GlobalKey<FormState>();
  final tableKey = GlobalKey<DataTableState<SchoolClassItemRes>>();

  @override
  void initState() {
    super.initState();
    //加载数据
    final model = context.read<SchoolClassViewModel>();
    model.loadInit(afterHandler: () => query(model));
  }

  void query(final SchoolClassViewModel model) => model.query(widget.schoolId);

  Widget buildQueryForm(final SchoolClassViewModel model) {
    Widget buildField(SchoolClassQueryField field,
        Widget Function(TextEditingController? c, String label) handler) {
      final label = field.label;
      final controller = model.getController(field);
      final child = handler.call(controller, label);
      return SizedBox(
        width: 128.w,
        child: InfoLabel(
          label: label,
          child: child,
        ),
      );
    }

    return Form(
      key: queryFormKey,
      child: Wrap(
        spacing: 5.w,
        children: [
          //入学年份
          buildField(
            SchoolClassQueryField.enterYear,
            (c, label) => TextFormBox(placeholder: label, controller: c),
          ),
          //班级名称
          buildField(
            SchoolClassQueryField.title,
            (c, label) => TextFormBox(placeholder: label, controller: c),
          ),
          //状态
          buildField(
            SchoolClassQueryField.status,
            (ctr, label) => ComboboxFormField(
              placeholder: Text(label),
              items: model.statusOpts,
              onChanged: (val) => ctr?.text = val ?? "1",
            ),
          ),
        ],
      ),
    );
  }

  Widget buildQueryBars(final SchoolClassViewModel model) => Wrap(
        spacing: 2.w,
        children: [
          //查询
          buttons.query(onPressed: () => query(model)),
          //重置
          buttons.reset(onPressed: () {
            queryFormKey.currentState?.reset();
            model.cleanQueryFields();
            query(model);
          }),
          //新增
          buttons.add(onPressed: () => editHandler(model, null)),
        ],
      );

  void editHandler(final SchoolClassViewModel model, final String? id) async {
    final isAdd = (id ?? '').isEmpty;
    final ret = await showDialog<bool>(
        context: context,
        builder: (context) {
          final size = MediaQuery.sizeOf(context);
          final padding = PageHeader.horizontalPadding(context);
          return ContentDialog(
            title: Text('${isAdd ? '新增' : '编辑'}班级'),
            constraints: BoxConstraints(
              maxWidth: size.width - padding * 2,
              maxHeight: size.height - padding * 2,
            ),
            content: ChangeNotifierProvider.value(
              value: model,
              builder: (context, _) => SchoolClassViewEdit(
                schoolId: widget.schoolId,
                id: id,
              ),
            ),
          );
        });
    if (ret ?? false) {
      query(model);
    }
  }

  @override
  Widget build(final BuildContext context) => Consumer<SchoolClassViewModel>(
        builder: (context, model, _) => ScaffoldPage.scrollable(
          header: Column(children: [
            PageHeader(title: const Text('班级列表')),
            Padding(
              padding: () {
                final padding = PageHeader.horizontalPadding(context);
                return EdgeInsetsDirectional.symmetric(horizontal: padding);
              }(),
              child: Row(children: [
                //查询条件
                buildQueryForm(model),
                //占位
                Expanded(child: Container()),
                //查询按钮
                buildQueryBars(model),
              ]),
            ),
            SizedBox(height: 15.h),
          ]),
          children: [
            //数据列表
            buildTable(model),
          ],
        ),
      );

  Widget buildTable(final SchoolClassViewModel model) {
    final labels = <String>['班级编码', '班级名称', '入学年份', '状态', '创建时间', '操作'];
    DataCell buildCell(String? Function() handler) => DataCell(Text(
          handler.call() ?? '',
          softWrap: false,
          overflow: TextOverflow.ellipsis,
        ));
    final dtFormat = 'yyyy-MM-dd HH:mm:ss';
    return DataTable<SchoolClassItemRes>(
      key: tableKey,
      model: model.queryModel,
      columns: labels.map((e) => DataColumn(label: Text(e))).toList(),
      onLoadData: () => query(model),
      onRowCallback: (row) => [
        // 班级编码
        buildCell(() => row.code),
        // 班级名称
        buildCell(() => row.title),
        // 入学年份
        buildCell(() => '${row.enterYear}'),
        //状态
        buildCell(() => appDictData.getLabel('status', row.status)),
        // 创建时间
        buildCell(() => dateUtils.format(dtFormat, row.createdAt)),
        // 操作
        DataCell(OverflowBar(
          spacing: 2.w,
          children: [
            //编辑
            buttons.modify(onPressed: () {
              final id = row.id;
              if (id.isNotEmpty) {
                editHandler(model, id);
              }
            }),
            //删除
            buttons.delete(onPressed: () {
              final id = row.id;
              if (id.isNotEmpty) {
                model.onDeleteHandler(schoolId: widget.schoolId, id: id);
              }
            }),
          ],
        )),
      ],
    );
  }
}
